import logging
from logging.handlers import RotatingFileHandler
# import pymysql
# pymysql.install_as_MySQLdb()
from celery import Celery
from flask_sqlalchemy import SQLAlchemy
from flask_wtf import CSRFProtect
from flask_mail import Mail
from flask import Flask
from flask_caching import Cache

from config import configs

db = SQLAlchemy()

# 使用wtf提供的csrf保护机制
csrf = CSRFProtect()

celery = Celery(__name__, broker=configs['develop'].CELERY_BROKER_URL)

mail = Mail()

cache = Cache(config={"CACHE_TYPE": "redis", "CACHE_REDIS_URL": "redis://10.100.14.131:6379/2"})


def setup_logging(level):
    # 业务逻辑已开启就加载日志
    # 设置日志的记录等级
    logging.basicConfig(level=level)  # 调试debug级
    # 创建日志记录器，指明日志保存的路径、每个日志文件的最大大小、保存的日志文件个数上限
    file_log_handler = RotatingFileHandler("logs/log", maxBytes=1024 * 1024 * 100, backupCount=10)
    # 创建日志记录的格式                 日志等级    输入日志信息的文件名 行数    日志信息
    formatter = logging.Formatter('%(levelname)s %(filename)s:%(lineno)d %(message)s')
    # 为刚创建的日志记录器设置日志记录格式
    file_log_handler.setFormatter(formatter)
    # 为全局的日志工具对象（应用程序实例app使用的）添加日后记录器
    logging.getLogger().addHandler(file_log_handler)


def create_app(envconfig):
    # setup_logging(configs[envconfig].LOGGING_LEVEL)

    app = Flask(__name__)
    config_obj = configs.get(envconfig, "default")
    app.config.from_object(config_obj)

    # 加载配置celery文件
    celery.conf.update(app.config)

    cache.init_app(app)
    db.init_app(app)
    csrf.init_app(app)
    mail.init_app(app)

    from app.app_1_0.cmdb import cmdb as cmdb_blueprint
    from .app_1_0.user import user_bp
    from .app_1_0 import api_1 as api_bp
    from app.app_1_0.auth import auth_bp

    # app.register_blueprint(cmdb_blueprint, url_prefix='/cmdb')
    app.register_blueprint(user_bp, url_prefix="/user")
    app.register_blueprint(api_bp, url_prefix="/")
    app.register_blueprint(auth_bp, url_prefix="/auth")


    # with app.app_context():

    return app
